<template>
  <div>
    <!-- 顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 输入框和按钮 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入搜索内容"
            v-model="queryInfo.query"
            clearable
            @clear="getTableList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getTableList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 插槽为了取出整行的数据 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditForm(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteEditRow(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="rightsToRole(scope.row)"
              >
              </el-button>
            </el-tooltip>
            <!-- {{ scope.row }} -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户表单区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addFormVisible"
      @close="resetAddForm"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
        ref="addFormRefs"
        status-icon
      >
        <el-form-item label="用户" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddForm">提交</el-button>
        <el-button type="info" @click="resetAddForm">重置</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户表单区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editFormVisible"
      @close="resetEditForm"
    >
      <el-form
        :model="editForm"
        label-width="70px"
        ref="editFormRef"
        :rules="editFormRules"
        status-icon
      >
        <el-form-item label="用户" prop="username">
          <el-input
            v-model="editForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitEditForm">提交</el-button>
        <el-button type="primary" @click="resetEditForm">重置</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="rightsToRoleVisible"
      @close="resetRightClassify"
    >
      <el-descriptions :column="1">
        <el-descriptions-item label="当前的用户">{{
          usermsg.username
        }}</el-descriptions-item>
        <el-descriptions-item label="当前的角色">{{
          usermsg.role_name
        }}</el-descriptions-item>

        <el-descriptions-item label="分配新角色">
          <!-- 下拉框 -->
          <el-select v-model="selectRoleId" clearable placeholder="请选择">
            <el-option
              v-for="item in rolelist"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rightsToRoleVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitRightsToRole(usermsg, selectRoleId)"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    // 邮箱的校验规则
    var checkEmail = (rule, value, cellback) => {
      if (!value) return cellback(new Error("请输入邮箱"));
      setTimeout(() => {
        const regEmail =
          /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (regEmail.test(value)) {
          return cellback();
        } else {
          cellback(new Error("请输入合法的邮箱"));
        }
      }, 1000);
    };

    // 手机号的校验规则
    var checkMobile = (rule, value, cellback) => {
      if (!value) return cellback(new Error("请输入手机号"));
      setTimeout(() => {
        const regMobile =
          /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;
        if (regMobile.test(value)) {
          return cellback();
        } else {
          cellback(new Error("请输入合法的手机号"));
        }
      }, 1000);
    };

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      tableData: [],
      total: 0,
      addFormVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "请输入长度在3到10个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 10,
            message: "请输入长度在6到10之间个字符",
            trigger: "blur",
          },
        ],
        email: [{ required: true, validator: checkEmail, trigger: "blur" }],
        mobile: [{ required: true, validator: checkMobile, trigger: "blur" }],
      },
      editFormVisible: false,
      editForm: {
        username: "",
        email: "",
        mobile: "",
      },
      //编辑用户的表单规则校验
      editFormRules: {
        email: [{ required: true, validator: checkEmail, trigger: "blur" }],
        mobile: [{ required: true, validator: checkMobile, trigger: "blur" }],
      },
      // 控制分配角色对话框关闭
      rightsToRoleVisible: false,
      // 一整行的数据
      usermsg: {},
      // 所有角色列表
      rolelist: [],
      // 当前选择器选中的角色id值
      selectRoleId: "",
    };
  },
  created() {
    this.getTableList();
  },
  methods: {
    async getTableList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.tableData = res.data.users;
      this.total = res.data.total;
    },
    // 更新每页条数的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getTableList();
    },
    // 更新页码的事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getTableList();
    },
    // 修改用户状态
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state;
        this.$message.error("修改用户状态失败");
      }
      this.$message.success("修改用户状态成功");
    },
    resetAddForm() {
      this.$refs.addFormRefs.resetFields();
    },
    // 提交添加用户的事件
    submitAddForm() {
      this.$refs.addFormRefs.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        // console.log(res);
        if (res.meta.status == 201) {
          this.$message.success("添加用户成功");
          // 控制对话框在提交后自动关闭并刷新列表
          this.addFormVisible = false;
          this.getTableList();
        } else if (res.meta.status == 400) {
          return this.$message.error(res.meta.msg);
        } else {
          return this.$message.error("添加用户失败");
        }
      });
    },
    // 重置表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields();
    },
    // 编辑中获取用户ID的事件
    showEditForm(userinfo) {
      axios
        .get(`users/${userinfo.id}`)
        // .then(({ data: res }) => {
        //   // console.log(res);
        //   if (res.meta.status !== 200) {
        //     return this.$message.error("未获取到该用户ID");
        //   } else {
        //     this.editForm = res.data;
        //     this.editFormVisible = true;
        //   }
        // })
        .then(({ data: res }) => {
          this.$message.success("获取到该用户ID");
          this.editForm = res.data;
          this.editFormVisible = true;
        })
        .catch(() => {
          this.$message.error("未获取到该用户ID");
        });
    },
    // 提交编辑用户信息
    submitEditForm() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        axios
          .put(`users/${this.editForm.id}`, this.editForm)
          .then(() => {
            this.$message.success("修改用户信息成功");
            this.getTableList();
            this.editFormVisible = false;
          })
          .catch(() => {
            this.$message.error("修改用户信息成功");
          });
      });
    },
    // 删除用户
    // deleteEditRow(id) {
    //   this.$confirm(
    //     "此操作将永久删除该文件, 是否继续?",
    //     "提示",
    //     {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning",
    //     }
    //   )
    //     .then(async () => {
    //       const { data: res } = await this.$http.delete(`users/${id}`);
    //       console.log(res);
    //       if (res.meta.status !== 200)
    //         return this.$message.error("删除用户失败");
    //       this.$message({ type: "success", message: "删除用户成功！" });
    //       this.getTableList();
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: "info",
    //         message: "已取消删除",
    //       });
    //     });
    // },
    deleteEditRow(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios
            .delete(`users/${id}`)
            .then(({ data: res }) => {
              if (res.meta.status == 400) {
                return this.$message.error("删除用户失败");
              } else {
                this.$message({
                  type: "success",
                  message: "删除用户成功",
                });
                this.getTableList();
              }
            })
            .catch(() => {
              this.$message({
                type: "error",
                message: "删除用户失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色
    rightsToRole(usermsg) {
      this.usermsg = usermsg;
      axios.get(`roles`).then(({ data: res }) => {
        // console.log(res);
        this.rolelist = res.data;
      });
      this.rightsToRoleVisible = true;
    },
    // 提交分配角色
    submitRightsToRole(usermsg, selectRoleId) {
      if (!selectRoleId) {
        return this.$message.error("请选择分配的角色");
      } else {
        axios
          .put(`users/${usermsg.id}/role`, { rid: selectRoleId })
          .then(({ data: res }) => {
            // console.log(res);
            this.rightsToRoleVisible = false;
            this.$message.success("已成功分配角色");
            this.getTableList();
          })
          .catch(() => {
            this.$message.error("分配角色失败");
          });
      }
    },
    // 监听分配角色对话框关闭
    resetRightClassify() {
      this.selectRoleId = "";
    },
  },
};
</script>

<style lang="scss" scoped>
</style>